package daobeauty.proxy.cglib;

import net.sf.cglib.core.NamingPolicy;
import net.sf.cglib.core.Predicate;
import net.sf.cglib.proxy.Enhancer;

import org.hibernate.SessionFactory;

import daobeauty.interceptor.MethodInterceptor;
import daobeauty.proxy.ProxyProvider;

/**
 * Created 08.09.2008
 * @author M. Serhat Cinar
 *
 */
public class CglibProxyProvider implements ProxyProvider {


	/* (non-Javadoc)
	 * @see daobeauty.proxy.ProxyProvider#generateProxy(java.lang.Class[], org.hibernate.SessionFactory, java.lang.Class, java.lang.Object, java.lang.Object[])
	 */
	public Object generateProxy(Class[] interfaces, SessionFactory sessionFactory, Class domainClass, Object target, Object[] delegates) {
		if (interfaces == null || interfaces.length < 1) {
			throw new IllegalArgumentException( "attempting to build proxy without any superclass or interfaces" );
		}
		
		final Enhancer enhancer = new Enhancer();
  		enhancer.setUseCache( false );
  		enhancer.setInterceptDuringConstruction( false );
//		if ( superClass != null ) {
//			enhancer.setSuperclass(superClass);
//		}
		if ( interfaces != null && interfaces.length > 0 ) {
			enhancer.setInterfaces( interfaces );
		}
		enhancer.setNamingPolicy(
			new NamingPolicy(){
				@SuppressWarnings("unused")
	 			public String getClassName(String prefix, String source, Object key, Predicate names){
	 				return source+"$CGLIB"+Integer.toHexString(key.hashCode());
	 			}
	 		}
		);
  		enhancer.setCallback(new InvocationHandlerAdapter(MethodInterceptor.create(sessionFactory, domainClass, target, delegates, interfaces)));
  		return enhancer.create();
	}
}
